package com.wnhoo.smartfishtank.app;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.wnhoo.smartfishtank.api.LM_User;
import com.wnhoo.smartfishtank.api.data.LM_AccessToken;
import com.wnhoo.smartfishtank.api.data.LM_Register;
import com.wnhoo.smartfishtank.api.other.MD5Util;
import com.wnhoo.smartfishtank.util.ShowToastUtil;
import com.wnhoo.smartfishtank.util.UIUtil;

import java.io.IOException;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import static android.content.Context.TELEPHONY_SERVICE;

/**
 * 作者：hankin on 2016/11/4 13:58
 * 邮箱：hankinhan@wnhoo.com
 * 功能：
 */
public class LoginRunnable implements Runnable {

    private Context context;
    private static final String TAG = "LoginRunnable";

    public LoginRunnable(Context context) {
        this.context = context;
    }


    public void initAccessToken() {
        Log.i(TAG, "激活手机");
//        String[] mac = getMacAddress();
        String[] mac =getTelephony();
        //尝试登录
        LM_AccessToken data_login = null;
        try {
            Log.i(TAG, "尝试用mac地址登陆账号" + mac[0]);
            Log.i(TAG, "尝试用mac地址登陆密码" + mac[1]);
            try {
                data_login = LM_User.login(false, mac[0], mac[1],UIUtil.isZh(context)?"cn":"en");
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.i(TAG, "尝试用mac地址登陆" + data_login+":"+(UIUtil.isZh(context)?"cn":"en"));
            if (data_login != null && data_login.getError_code() == 0 && !data_login.getToken().equals("null")) {
                //登录成功
                LMAPP.token_default = data_login.getToken();
//                Wnhoo.writeSPFAccessToken(Wnhoo.token_default);
                Log.i(TAG, "服务器给的token结果是" + LMAPP.token_default);
            } else {
                //登录失败，尝试注册
                LM_Register data_register = LM_User.register(true, mac[0], mac[1]);
                Log.i(TAG, "登录失败，注册结果" + data_register);
                if (data_register != null && (data_register.getError_code() == 0 || data_register.getError_code() == 501)) {
                    //注册成功，或者帐号已经存在
                    Log.i("i", "====================data_login" + data_register.getError_code());
                    Log.d(TAG, "注册成功，或者帐号已经存在");
                    data_login = LM_User.login(false, mac[0], mac[1], UIUtil.isZh(context)?"cn":"en");
                    if (data_login != null && data_login.getError_code() == 0 && !data_login.getToken().equals("null")) {
                        //登录成功
                        LMAPP.token_default = data_login.getToken();
                        Log.i(TAG, "服务器给的token结果是" + LMAPP.token_default);
                    }
                } else {
                    //注册失败，提醒用户激活手机失败，请检查网络，再重试。
                    Log.d(TAG, "注册失败，提醒用户激活手机失败，请检查网络，再重试。");
                }
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            initJPush();
        }
    }

    @Override
    public void run() {
        initAccessToken();
    }


    /**
     * 获取设备MAC地址
     * <p>需添加权限 android.permission.ACCESS_WIFI_STATE</p>
     *
     * @return MAC地址
     */
    public static String[] getMacAddress() {
        String macAddress = null;
//        try {
//            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address");
//            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
//            LineNumberReader reader = new LineNumberReader(ir);
//            macAddress = reader.readLine().replaceAll(":", "");
//        } catch (IOException ex) {
//            ex.printStackTrace();
//        }
//        LM_DESLemoniot des = new LM_DESLemoniot();
//        String passwd = des.desCryptoHexString("SmartFish", macAddress);
        return new String[]{"com_wnhoo_smartfish", "com_wnhoo_smartfish"};
    }

    public  String[] getTelephony(){
        TelephonyManager TelephonyMgr = (TelephonyManager)context.getSystemService(TELEPHONY_SERVICE);
        String szImei = TelephonyMgr.getDeviceId();
        Log.i(TAG,"手机的标识码"+szImei);
        return new String[]{szImei,MD5(szImei)};
    }
    private static String MD5(String data) {
        MD5Util getMD5 = new MD5Util();
        return getMD5.md5Signature(data);
    }
    /**
     * 初始化极光推送相关设置
     */
    private void initJPush() {
        JPushInterface.setAlias(context, getServerAccessToken(), new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {
            }
        });
    }

    /**
     * 直接用token注册极光推送的别名，会出问题，因为别名中不能有“—”，去掉token中的“—”
     *
     * @return
     */
    private String getServerAccessToken() {
        String token = LMAPP.getAccessToken();
        if (token != null) {
            token = token.replaceAll("-", "_");
        }
        Log.i(TAG, "新的token" + token);
        return token;
    }

    public void sendMessageToUI(int what, Object obj) {
        Message message = Message.obtain();
        message.what = what;
        message.obj = obj;
        mhandler.sendMessage(message);
    }

    public Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    LM_AccessToken data_login = (LM_AccessToken) msg.obj;
                    ShowToastUtil.show((Application) context, data_login.getError_code() + ":" + data_login.getToken());
                    break;
                case 1:
                    LM_Register data_register = (LM_Register) msg.obj;
                    ShowToastUtil.show((Application) context, "注册结果"+data_register.getError_code()+"");
                    break;
                case 3:
                    ShowToastUtil.show((Application) context, "登陆的账号是"+msg.obj);
                    break;
                case 4:
                    ShowToastUtil.show((Application) context, "登陆的密码是"+msg.obj);
                    break;
                default:
                    break;
            }
        }
    };
}